package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.xbongbong.paas.script.help.ApiRequestWrapper;
import com.xbongbong.paas.toolbox.util.DigestUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * api回调测试-接收端
 * @author 李少杰
 * @version v1.0.0
 * @date 2021/10/12 09:57
 */
@SuppressWarnings("deprecation")
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/callback/")
public class ApiCallBackTestController {
    private static final Logger LOG = LoggerFactory.getLogger(ApiCallBackTestController.class);

    /**
     * 测试token
     */
    private static final Map<String, String> TOKEN_MAP = new HashMap<>();

    /**
     * 安全验证码
     */
    private static final String CODE = "97cca4cde7240ce6094270fd061cca22";


    @RequestMapping(value = "/test", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String checkSign(HttpServletRequest httpServletRequest) {
        XbbResponse<BaseVO> response;
        try {
            JSONObject params = getParams(httpServletRequest);
            LOG.info("callback request= " + JSON.toJSONString(params));
            String checkSign = httpServletRequest.getHeader("sign");
            String token = TOKEN_MAP.get(params.getString("corpid"));
            String sign = DigestUtil.Encrypt(params.toJSONString() + token, "SHA-256");
            if (checkSign.equals(sign)) {
                LOG.info("callback check success!");
            }
            response = new XbbResponse<>(new BaseVO());
        } catch (Exception e) {
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, "request analysis error!");
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/token/set", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String setToken(HttpServletRequest httpServletRequest) {
        XbbResponse<BaseVO> response;
        String code = httpServletRequest.getHeader("code");
        if (!StringUtil.isEmpty(code) && code.equals(CODE)) {
            TOKEN_MAP.put(httpServletRequest.getParameter("corpid"), httpServletRequest.getParameter("token"));
            LOG.info("callBack-test: token reset success!---tokenMap:" + TOKEN_MAP);
            response = new XbbResponse<>(new BaseVO());
        } else {
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, "code error!");
        }
        return JSON.toJSONString(response);
    }

    public static JSONObject getParams(HttpServletRequest request) throws IOException {
        LinkedHashMap params;

        ApiRequestWrapper requestWrapper = new ApiRequestWrapper(request);
        byte[] requestWrapperBody = requestWrapper.getBody();
        String requestWrapperString = new String(requestWrapperBody, StandardCharsets.UTF_8);
        params = JSON.parseObject(requestWrapperString, LinkedHashMap.class, Feature.OrderedField);
        JSONObject requestJsonObject = new JSONObject(true);
        requestJsonObject.putAll(params);
        return requestJsonObject;
    }
}
